package com.ml.mall.service.dashboard.impl;

import com.ml.mall.bean.req.dashboard.DashboardDto;
import com.ml.mall.bean.req.dashboard.DashboardByPSPQueryDto;
import com.ml.mall.bean.req.delivery.DeliveryDashboardReq;
import com.ml.mall.bean.res.dashboard.*;
import com.ml.mall.bean.res.dashboard.vo.DashBoardNumByPurchaserVo;
import com.ml.mall.bean.res.dashboard.vo.DashBoardTopTenSpentCategoryVo;
import com.ml.mall.bean.res.dashboard.vo.DashBoardTopTenSpentSupplierVo;
import com.ml.mall.bean.res.partner.PartnerDashboardQueryRes;
import com.ml.mall.bean.res.partner.vo.PartnerDayDetailVo;
import com.ml.mall.bean.res.partner.vo.PartnerSupVarActiveNumVo;
import com.ml.mall.bean.res.partner.vo.PartnerSupVarNumVo;
import com.ml.mall.bean.res.supplier.SupplierDashboardQueryRes;
import com.ml.mall.bean.res.supplier.vo.SupplierDayDetailVo;
import com.ml.mall.bean.vo.variant.VariantCountVO;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.company.SysCompanyAddr;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.company.SysCompanyAddrMapper;
import com.ml.mall.mapper.company.SysCompanyMapper;
import com.ml.mall.mapper.delivery.SysOrderDeliveryMapper;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.mapper.partner.SysOrderPartnerMapper;
import com.ml.mall.mapper.supplier.SysOrderSupplierMapper;
import com.ml.mall.mapper.variant.SysProductVariantMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.dashboard.DashboardService;
import com.ml.mall.utils.DateUtils;
import com.ml.mall.utils.DimDateTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *   @description    :description
 *   @author         :zxm
 *   @date           :2021/5/24
 *   @version        :1.0
**/
@Service
@Slf4j
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private SysOrderMapper sysOrderMapper;
    @Autowired
    private SysOrderSupplierMapper sysOrderSupplierMapper;
    @Autowired
    private SysOrderDeliveryMapper sysOrderDeliveryMapper;
    @Autowired
    private SysCompanyAddrMapper sysCompanyAddrMapper;

    @Autowired
    private SysOrderPartnerMapper sysOrderPartnerMapper;
    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysProductVariantMapper sysProductVariantMapper;

    @Override
    public List<RecentOrderRes> queryRecentOrder() {
        SysUser currentUser = JwtUtil.getCurrentUser();
        currentUser.getRoleType();
        List<RecentOrderRes> orderResList = new ArrayList<>();
        if (CommonConsts.ROLE_TYPE_ADMIN.equals(currentUser.getRoleType())){
            orderResList = sysOrderMapper.selectRecentOrder();
        }else if(CommonConsts.ROLE_TYPE_SUPPLIER.equals(currentUser.getRoleType())){
            orderResList = sysOrderSupplierMapper.selectRecentOrder(currentUser.getCompanyId());
        }else if(CommonConsts.ROLE_TYPE_PURCHASE.equals(currentUser.getRoleType())){
            orderResList = sysOrderMapper.selectRecentOrderByPurchaser(currentUser.getCompanyId());
        }
        return orderResList;
    }

    @Override
    public List<RecentDeliveryRes> queryRecentDelivery(DeliveryDashboardReq req) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        if(req.getTimeDate() == null){
            req.setTimeDate(new Date());
        }
        String timeDate = format.format(req.getTimeDate());
        List<RecentDeliveryRes> deliveryResList = new ArrayList<>();
        switch (currentUser.getRoleType()){
            case 1: // 管理员查询全部
                deliveryResList = sysOrderDeliveryMapper.selectRecentDeliveryByAdmin(req.getCompanyName(),timeDate);
                break;
            case 2: // 合作伙伴查询自己邀请的商户
                SysCompany sysCompany = sysCompanyMapper.selectByCompanyId(currentUser.getCompanyId());
                if(sysCompany == null){
                    return null;
                }
                deliveryResList = sysOrderDeliveryMapper.selectRecentDeliveryByPartner(sysCompany.getInviteCode(),timeDate);
                break;
            case 3: // 卖家查询自己出卖的物流信息
                deliveryResList = sysOrderDeliveryMapper.selectRecentDeliveryBySupplier(currentUser.getCompanyId(),timeDate);
                break;
            case 4:  // 买家查询自己购买的物流信息
                deliveryResList = sysOrderDeliveryMapper.selectRecentDeliveryByPurchaser(currentUser.getCompanyId(),timeDate);
                break;
            default:
                throw new BizException(CommonEnum.ILLEGAL_REQ_ERROR);
        }
        if(deliveryResList == null || deliveryResList.size() == 0){
            return null;
        }
//        for (RecentDeliveryRes deliveryRes:deliveryResList) {
//            SysCompanyAddr shopAddr = sysCompanyAddrMapper.selectShopAddrByCompanyId(deliveryRes.getPurchaseId());
//            deliveryRes.setPurchaseCompanyShopAddr(shopAddr);
//        }
        return deliveryResList;
    }

    @Override
    public DashboardAdminRes queryAdminDashboard(DashboardDto dto) {
        DashboardAdminRes dashboardAdminRes = new DashboardAdminRes();
        String beginDateStr = dto.getTimeBegin();
        String endDateStr = dto.getTimeEnd();
        // 指定日期订单数
        dashboardAdminRes = sysOrderMapper.sumTotalAppointDateOrder(beginDateStr, endDateStr);
        log.info("dashboardAdminRes==={}",dashboardAdminRes);
        // 指定年月日内的订单（每天的订单）
        List<DashboardAppointDateOrderRes> dashboardAppointDateOrderRes = sysOrderMapper.sumAppointDateStrOrder(beginDateStr, endDateStr);
        if(dashboardAppointDateOrderRes != null && dashboardAppointDateOrderRes.size()>0){
            dashboardAdminRes.setAppointDateOrderRes(dashboardAppointDateOrderRes);
        }
        log.info("dashboardAdminRes=222=={}",dashboardAdminRes);
        // 总的订单数量
//        DashboardRes dashboardRes = sysOrderMapper.sumTotalOrder();
//        dashboardAdminRes.setTotalOrderNum(dashboardRes.getTotalOrderNum());
//        dashboardAdminRes.setTotalSales(dashboardRes.getTotalSales());


        //variant数量
        VariantCountVO vr = sysProductVariantMapper.selectVariantCount();

        // 总的供应商和采购商
        DashboardCompanyRes dashboardCompanyRes = sysCompanyMapper.sumTotalCompany();
        dashboardAdminRes.setPurchaseNum(dashboardCompanyRes.getPurchaseNum());
        dashboardAdminRes.setPurchaseActiveNum(dashboardCompanyRes.getPurchaseActiveNum());
        dashboardAdminRes.setSupplierNum(dashboardCompanyRes.getSupplierNum());
        dashboardAdminRes.setSupplierActiveNum(dashboardCompanyRes.getSupplierActiveNum());
        dashboardAdminRes.setVariantTotalCount(vr.getVariantTotalCount());
        dashboardAdminRes.setVariantPerFormingCount(vr.getVariantPerFormingCount());

        return dashboardAdminRes;
    }

    @Override
    public DashBoardPurchaserQueryRes queryPurchaserDashboard(DashboardByPSPQueryDto dto) {
        Long purchaserId = JwtUtil.getCurrentUser().getCompanyId();
        DashBoardPurchaserQueryRes purchaserQueryRes = new DashBoardPurchaserQueryRes();
        String timeBegin = dto.getTimeBegin();
        String timeEnd = dto.getTimeEnd();
        //对应的订单数量
        DashBoardNumByPurchaserVo numByPurchaserVo = sysOrderMapper.selectDashboardByPurchaser(purchaserId, timeBegin, timeEnd);
        //消费前十的目录信息
        List<DashBoardTopTenSpentCategoryVo> topTenSpentCategoryList = sysOrderMapper.selectTopTenSpentCategory(purchaserId, timeBegin, timeEnd);
        //消费前十的供货商信息
        List<DashBoardTopTenSpentSupplierVo> topTenSpentSupplierList = sysOrderMapper.selectTopTenSpentSupplier(purchaserId, timeBegin, timeEnd);
        purchaserQueryRes.setTotalInvoiceNum(numByPurchaserVo.getTotalInvoceNum())
            .setTotalSpentNum(numByPurchaserVo.getTotalSpentNum())
            .setTotalProductNum(numByPurchaserVo.getTotalProductNum())
            .setTopTenSpentCategoryList(topTenSpentCategoryList)
            .setTopTenSpentSupplierList(topTenSpentSupplierList);
        return purchaserQueryRes;
    }

    @Override
    public SupplierDashboardQueryRes querySupplierDashboard(DashboardByPSPQueryDto dto)throws Exception {

        Long supplierId = JwtUtil.getCurrentUser().getCompanyId();
        log.info("supplierId==={}",supplierId);
       // SimpleDateFormat YMd = DateUtils.dayFormat.get();
        //SimpleDateFormat MMdd = DateUtils.ddMMFormat.get();
        String timeBegin = dto.getTimeBegin();
        String timeEnd = dto.getTimeEnd();

        //仪表盘信息查询
        SupplierDashboardQueryRes supplierDashboardQueryRes = sysOrderSupplierMapper.selectSalesPoNum(supplierId, timeBegin, timeEnd);
        Integer totalRejectOrder = sysOrderSupplierMapper.selectRejectOrder(supplierId, timeBegin, timeEnd);
        Integer totalDeliveredOrder = sysOrderSupplierMapper.selectDeliveredOrder(supplierId, timeBegin, timeEnd);
        Integer totalVarantOrder = sysOrderSupplierMapper.selectVariantNum(supplierId, timeBegin, timeEnd);

        //查询为空的情况
        if (totalRejectOrder==null){
            totalRejectOrder = 0;
        }
        if (totalDeliveredOrder==null){
            totalDeliveredOrder = 0;
        }
        if (totalVarantOrder==null){
            totalVarantOrder = 0;
        }

        //查询限定日期内每天的详细数据
        List<SupplierDayDetailVo> supplierDayDetailVos = sysOrderSupplierMapper.selectSupplierDateDetailByTimeLine(supplierId,timeBegin,timeEnd);
        log.info("supplierDayDetailVos==={}",supplierDayDetailVos);
        supplierDayDetailVos = DimDateTransformUtils.getCurDateMonthDataInit(timeBegin,timeEnd,supplierDayDetailVos);
        log.info("supplierDayDetailVos==2222={}",supplierDayDetailVos);

        //进行数据封装
        if(supplierDashboardQueryRes==null){
            return null;
        }
        supplierDashboardQueryRes.setTotalRejectOrder(totalRejectOrder)
            .setTotalDeliveredOrder(totalDeliveredOrder)
            .setTotalVariantNum(totalVarantOrder)
            .setSupplierDayDetailVos(supplierDayDetailVos);
        return supplierDashboardQueryRes;
    }

    @Override
    public PartnerDashboardQueryRes queryPartnerDashboard(DashboardByPSPQueryDto dto) throws Exception{

        Long partnerId = JwtUtil.getCurrentUser().getCompanyId();

       // SimpleDateFormat YMd = DateUtils.dayFormat.get();
        //SimpleDateFormat MMdd = DateUtils.ddMMFormat.get();
        String timeBegin = dto.getTimeBegin();
        String timeEnd = dto.getTimeEnd();

    //仪表盘信息查询
        PartnerDashboardQueryRes partnerDashboardQueryRes = sysOrderPartnerMapper.selectSalesAndPo(partnerId, timeBegin, timeEnd);
        Integer completedPO = sysOrderPartnerMapper.selectCompletedPO(partnerId, timeBegin, timeEnd);
        Integer processingPO = sysOrderPartnerMapper.selectProcessingPO(partnerId, timeBegin, timeEnd);
        PartnerSupVarNumVo partnerSupVarNumVo = sysOrderPartnerMapper.selectSupAndVarNum(partnerId);
        PartnerSupVarActiveNumVo partnerSupVarActiveNumVo = sysOrderPartnerMapper.selectSupAndVarActiveNum(partnerId, timeBegin, timeEnd);

        //查询为空的情况
        if (completedPO==null){
            completedPO = 0;
        }
        if (processingPO==null){
            processingPO = 0;
        }
        if (partnerSupVarNumVo==null){
            partnerSupVarNumVo = new  PartnerSupVarNumVo();
        }


        //查询限定日期内每天的详细数据
        List<PartnerDayDetailVo> partnerDayDetailVos = sysOrderPartnerMapper.selectPartnerDateDetailByTimeLine(partnerId, timeBegin,timeEnd);
        partnerDayDetailVos = DimDateTransformUtils.getCurDateMonthDataInit2(timeBegin,timeEnd,partnerDayDetailVos);

      if(partnerDashboardQueryRes==null){
          return null;
      }

        //封装
        partnerDashboardQueryRes.setTotalCompletedPO(completedPO)
            .setTotalProcessingPO(processingPO)
            .setDayDetail(partnerDayDetailVos)
            .setSupplierNum(partnerSupVarNumVo.getSupplierNum())
            .setSupplierActiveNum(partnerSupVarActiveNumVo.getSupplierActiveNum())
            .setVariantNum(partnerSupVarNumVo.getVariantNum()) //VariantNum 实际上是所有变体的数量
            .setVariantActiveNum(partnerSupVarActiveNumVo.getVariantActiveNum()); //VariantActiveNum() 作为活跃的变体总数量；前段显示为perfomNum
        return partnerDashboardQueryRes;
    }
}
